<template>
    <div class="detail-container">
    <div style="margin-top: 20px">
        <el-steps :active="formatStepStatus(order.orderStatus)" finish-status="success" align-center>
            <el-step
                    v-for="(step, index) in steps"
                    :key="index"
                    :title="step.title"
                    :description="getDescription(index)"
            ></el-step>
        </el-steps>
    </div>
    <el-card shadow="never" style="margin-top: 15px">
        <div class="operate-container">
            <i class="el-icon-warning color-danger" style="margin-left: 20px"></i>
            <span class="color-danger">当前销售订单状态：{{this.status[parseInt(order.orderStatus)-1]}}</span>
            <!--<div class="operate-button-container" v-show="order.orderStatus==='1'">-->
                <!--<el-button size="mini" @click="showUpdateReceiverDialog">修改收货人信息</el-button>-->
                <!--<el-button size="mini" @click="showUpdateMoneyDialog">修改费用信息</el-button>-->
                <!--<el-button size="mini" @click="showMessageDialog">发送站内信</el-button>-->
                <!--<el-button size="mini" @click="showCloseOrderDialog">关闭订单</el-button>-->
                <!--<el-button size="mini" @click="showMarkOrderDialog">备注订单</el-button>-->
            <!--</div>-->
            <!--<div class="operate-button-container" v-show="order.orderStatus===1">-->
                <!--<el-button size="mini" @click="showUpdateReceiverDialog">修改收货人信息</el-button>-->
                <!--<el-button size="mini" @click="showMessageDialog">发送站内信</el-button>-->
                <!--<el-button size="mini">取消订单</el-button>-->
                <!--<el-button size="mini" @click="showMarkOrderDialog">备注订单</el-button>-->
            <!--</div>-->
            <!--<div class="operate-button-container" v-show="order.orderStatus===2||order.orderStatus===3">-->
                <!--<el-button size="mini" @click="showLogisticsDialog">订单跟踪</el-button>-->
                <!--<el-button size="mini" @click="showMessageDialog">发送站内信</el-button>-->
                <!--<el-button size="mini" @click="showMarkOrderDialog">备注订单</el-button>-->
            <!--</div>-->
            <!--<div class="operate-button-container" v-show="order.orderStatus===4">-->
                <!--<el-button size="mini" @click="handleDeleteOrder">删除订单</el-button>-->
                <!--<el-button size="mini" @click="showMarkOrderDialog">备注订单</el-button>-->
            <!--</div>-->
        </div>
        <div style="margin-top: 20px">
            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
            <span class="font-small">基本信息</span>
        </div>
        <div class="table-layout">
            <el-row>
                <el-col :span="8" class="table-cell-title">订单编号</el-col>
                <el-col :span="8" class="table-cell-title">创建时间</el-col>
                <el-col :span="8" class="table-cell-title">客户名称</el-col>

            </el-row>
            <el-row>
                <el-col :span="8" class="table-cell">{{order.orderId}}</el-col>
                <el-col :span="8" class="table-cell">{{order.orderDate}}</el-col>
                <el-col :span="8" class="table-cell">{{customer.customerName}}</el-col>

            </el-row>
            <el-row>
<!--                <el-col :span="8" class="table-cell-title">配送方式</el-col>-->
              <el-col :span="8" class="table-cell-title">支付方式</el-col>
              <!--                <el-col :span="4" class="table-cell-title">订单来源</el-col>-->
              <el-col :span="8" class="table-cell-title">订单类型</el-col>
                <el-col :span="8" class="table-cell-title">配送单号</el-col>
<!--                <el-col :span="4" class="table-cell-title">自动确认收货时间</el-col>-->
<!--                <el-col :span="4" class="table-cell-title">订单可得优币</el-col>-->
<!--                <el-col :span="4" class="table-cell-title">订单可得成长值</el-col>-->
<!--                <el-col :span="4" class="table-cell-title">活动信息</el-col>-->
            </el-row>
            <el-row>
<!--                <el-col :span="8" class="table-cell">{{orderTrace.transportMode}}</el-col>-->
              <el-col :span="8" class="table-cell">{{paymentType[parseInt(order.paymentMethod)-1]?.dictLabel}}</el-col>
              <!--                <el-col :span="4" class="table-cell">{{order.referenceId}}</el-col>-->
              <el-col :span="8" class="table-cell">{{businessType[parseInt(order.businessType)-1]?.dictLabel}}</el-col>
                <el-col :span="8" class="table-cell">{{orderTrace.logisticsNumber}}</el-col>
<!--                <el-col :span="4" class="table-cell">{{order.autoConfirmDay}}天</el-col>-->
<!--                <el-col :span="4" class="table-cell">{{order.integration}}</el-col>-->
<!--                <el-col :span="4" class="table-cell">{{order.growth}}</el-col>-->
<!--                <el-col :span="4" class="table-cell">-->
<!--                    <el-popover-->
<!--                            placement="top-start"-->
<!--                            title="活动信息"-->
<!--                            width="200"-->
<!--                            trigger="hover"-->
<!--                            :content="order.promotionInfo">-->
<!--                        <span slot="reference">{{order.promotionInfo | formatLongText}}</span>-->
<!--                    </el-popover>-->
<!--                </el-col>-->
            </el-row>
        </div>
<!--        <div style="margin-top: 20px">-->
<!--            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>-->
<!--            <span class="font-small">收货人信息</span>-->
<!--        </div>-->
<!--        <div class="table-layout">-->
<!--            <el-row>-->
<!--                <el-col :span="6" class="table-cell-title">收货人</el-col>-->
<!--                <el-col :span="6" class="table-cell-title">手机号码</el-col>-->
<!--                <el-col :span="6" class="table-cell-title">邮政编码</el-col>-->
<!--                <el-col :span="6" class="table-cell-title">收货地址</el-col>-->
<!--            </el-row>-->
<!--            <el-row>-->
<!--                <el-col :span="6" class="table-cell">{{customerAddr.consignee}}</el-col>-->
<!--                <el-col :span="6" class="table-cell">{{customerAddr.phone}}</el-col>-->
<!--                <el-col :span="6" class="table-cell">{{customerAddr.zipcode}}</el-col>-->
<!--                <el-col :span="6" class="table-cell">{{this.getAddr()}}</el-col>-->
<!--            </el-row>-->
<!--        </div>-->
        <div style="margin-top: 20px">
            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
            <span class="font-small">商品信息</span>
        </div>
        <el-table :data="enrichedOrderDetails"  :span-method="objectSpanMethod"  style="width: 100%;margin-top: 20px" border>
          <el-table-column prop="customerAddr" label="配送地址" width="400" align="center"></el-table-column>
            <el-table-column prop="productId" label="商品编码" width="180"></el-table-column>
            <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
<!--            <el-table-column prop="productCategory" label="商品类别" width="180"></el-table-column>-->
            <el-table-column prop="source" label="生产商" width="180"></el-table-column>
            <el-table-column prop="subtotal" label="单价" width="180"></el-table-column>
            <el-table-column prop="productSalesQuantity" label="销售数量" width="180"></el-table-column>
            <el-table-column prop="totalAmount" label="小计" width="180"></el-table-column>
            <el-table-column prop="totalAmount" label="总金额" width="180"></el-table-column>
            <el-table-column prop="warehouseCode" label="仓库编码" width="180"></el-table-column>
            <el-table-column prop="remark" label="备注" width="180"></el-table-column>
        </el-table>
        <div style="float: right;margin: 20px">
            合计：<span class="color-danger">￥{{order.orderTotal}}</span>
        </div>
        <div style="margin-top: 60px">
            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
            <span class="font-small">费用信息</span>
        </div>
        <div class="table-layout" style="padding-bottom: 20px">
            <el-row>
                <el-col :span="6" class="table-cell-title">商品合计</el-col>
                <el-col :span="6" class="table-cell-title">运费</el-col>
                <el-col :span="6" class="table-cell-title">优惠券</el-col>
                <el-col :span="6" class="table-cell-title">积分抵扣</el-col>
            </el-row>
            <el-row>
                <el-col :span="6" class="table-cell">￥{{order.orderTotal}}</el-col>
                <el-col :span="6" class="table-cell">￥{{order.freightAmount || 0}}</el-col>
                <el-col :span="6" class="table-cell">-￥{{order.couponAmount || 0 }}</el-col>
                <el-col :span="6" class="table-cell">-￥{{order.integrationAmount || 0}} </el-col>
            </el-row>
            <el-row>
                <el-col :span="6" class="table-cell-title">活动优惠</el-col>
                <el-col :span="6" class="table-cell-title">折扣金额</el-col>
                <el-col :span="6" class="table-cell-title">订单总金额</el-col>
                <el-col :span="6" class="table-cell-title">应付款金额</el-col>
            </el-row>
            <el-row>
                <el-col :span="6" class="table-cell">-￥{{order.promotionAmount || 0}}</el-col>
                <el-col :span="6" class="table-cell">-￥{{order.discountAmount || 0}}</el-col>
                <el-col :span="6" class="table-cell">
                    <span class="color-danger">￥{{order.orderTotal || 0}}</span>
                </el-col>
                <el-col :span="6" class="table-cell">
                    <span class="color-danger">￥{{order.orderTotal || 0}}</span>
                </el-col>
            </el-row>
        </div>
      <div style="margin-top: 60px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">发票信息</span>
      </div>

      <div style="margin-top: 20px; width: 80%; margin-left: 10%">
        <image-upload
          v-model="order.invoiceInfo"
          :disable="true"
          :limit="5"
          :multiple="false"
          :file-type="['jpg','jpeg','png','pdf']"
          :is-show-tip="false"
      ></image-upload>
      </div>


      <div style="margin-top: 20px">
         <span slot="footer" class="dialog-footer" style="margin-left: 47% ; ">
                 <el-button @click="handleBack()">返 回</el-button>
                </span>
      </div>


        <!--<div style="margin-top: 20px">-->
            <!--<svg-icon icon-class="marker" style="color: #606266"></svg-icon>-->
            <!--<span class="font-small">操作信息</span>-->
        <!--</div>-->
        <!--<el-table style="margin-top: 20px;width: 100%"-->
                  <!--ref="orderHistoryTable"-->
                  <!--:data="order.historyList" border>-->
            <!--<el-table-column label="操作者"  width="120" align="center">-->
                <!--<template slot-scope="scope">-->
                    <!--{{scope.row.operateMan}}-->
                <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="操作时间"  width="160" align="center">-->
                <!--<template slot-scope="scope">-->
                    <!--{{formatTime(scope.row.createTime)}}-->
                <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="订单状态"  width="120" align="center">-->
                <!--<template slot-scope="scope">-->
                    <!--{{scope.row.orderStatus | formatStatus}}-->
                <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="付款状态"  width="120" align="center">-->
                <!--<template slot-scope="scope">-->
                    <!--{{scope.row.orderStatus | formatPayStatus}}-->
                <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="发货状态"  width="120" align="center">-->
                <!--<template slot-scope="scope">-->
                    <!--{{scope.row.orderStatus | formatDeliverStatus}}-->
                <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="备注" align="center">-->
                <!--<template slot-scope="scope">-->
                    <!--{{scope.row.note}}-->
                <!--</template>-->
            <!--</el-table-column>-->
        <!--</el-table>-->
    </el-card>
    </div>
</template>

<script>
    import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/system/order.js";
    import { getCustomerList, getInfo} from "@/api/system/info.js";
    import {getData,getDicts} from "@/api/system/dict/data.js"
    import {getCustomer, getCustomerAddr} from "../../api/system/addr.js";
    import {getDetail} from "@/api/system/detail.js";
    import {getMerInfo} from "../../api/system/merinfo.js";
    import { useDict } from '@/utils/dict.js'
    const { payment_meth, order_status, business_type } = useDict('payment_meth', 'order_status', 'business_type');
    const router = useRouter();
    import { listTrace, getTrace, delTrace, addTrace, updateTrace } from "@/api/system/trace.js";
    import ImageUpload from "@/components/ImageUpload/index.vue";
    import ImagePreview from "@/components/ImagePreview/index.vue";


    export default {
        name: "orderDetails",
      components: {ImagePreview, ImageUpload},

        data() {
            return {
                order: {},
                payment:{},
                businessType:{},
                paymentType:{},
                business:{},
                customerAddr:{},
                merlist:[],
                merdetail:{},
                orderTrace:{},
                order_status : useDict('order_status'),
                payment_meth:useDict('payment_meth'),
                 business_type:useDict('business_type'),
                spanMap:{},
                enrichedOrderDetails: [],
                customer:{
                    customerId:null,
                    customerName:null,
                    businessType:null,
                    customerEmail:null,
                    contactInfo:null,
                    realNameId:null

                },
                steps: [
                    { title: "待确认" },
                    { title: "待支付" },
                    { title: "已支付" },
                    { title: "待发货" },
                    { title: "已发货" },
                    { title: "运输中" },
                    { title: "派送中" },
                    { title: "待签收" },
                    { title: "已签收" }
                ],
                status: [
                    "待确认","待支付","已支付","待发货","已发货","运输中","派送中","待签收","已签收",
                ]
            }
        },
        mounted() {
            this.id = this.list = this.$route.query.id;
          this.order_status =useDict('order_status'),
              console.log("order_status",this.order_status);

            this.loadOrderAndCustomer();


        },

        methods:{

         loadOrderAndCustomer() {

            getOrder(this.id).then(response => {
              this.order = response.data;
              this.getDictsType();
              this.getCustomerAddr();
              this.getMerList();
              this.getMerDetail();
              this.getTrace();
              return this.getCustomer();
            }).then(() => {})
               .catch(error => {
                        console.error('获取订单或客户信息失败:', error);
                    });
            },
            getCustomer() {
                if (!this.order.customerId) {
                    console.warn('没有有效的 customerId');
                    return Promise.resolve();
                }


                return getInfo(this.order.customerId).then(response => {
                    this.customer = response.data;
                }).catch(error => {
                    console.error('获取客户信息失败:', error);
                    throw error;
                });
            },

            handleBack(){
                this.$tab.closeOpenPage(this.$route);
                this.$router.go(-1);
            },
            getTrace(){
                getTrace(this.order.orderId).then(response =>{
                    this.orderTrace = response.data;
                })
            },


            getMerDetail(){
             getMerInfo(1).then(response =>{
                 this.merdetail = response.data;
             }).catch(error =>{
                 console.error(error);
                 throw error;
             })
            },

          calculateSpans() {
            const spans = [];
            let pos = 0;
            const map = new Map();

            // 按地址分组
            this.enrichedOrderDetails.forEach((item, index) => {
              const key = item.customerAddr;
              if (map.has(key)) {
                map.get(key).push(index);
              } else {
                map.set(key, [index]);
              }
            });

            // 生成span配置
            map.forEach((indexes) => {
              indexes.forEach((i, idx) => {
                spans[i] = idx === 0 ? [indexes.length, 1] : [0, 0];
              });
            });

            this.spanMap = spans;
          },

          objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            // 只在配送地址列合并
            if (columnIndex === 0) {  // 根据实际列索引调整
              return this.spanMap[rowIndex] || [1, 1];
            }
          },

          async fetchAndEnrichOrderDetails() {
            try {
              const response = await getDetail(this.order.orderId);
              this.merlist = response.data;
              console.log("merlist", this.merlist);

              // 计算总金额
              const total = this.merlist.reduce((sum, item) => {
                return sum + (parseFloat(item.totalAmount) || 0);
              }, 0);
              this.order.orderTotal = total.toFixed(2);

              // 获取所有商品信息
              const productIds = [...new Set(this.merlist.map(item => item.productId))];
              const productPromises = productIds.map(productId =>
                  getMerInfo(productId).then(response => response.data)
              );
              console.log("productIds", productIds);
              console.log("productPromises", productPromises);
              const productInfos = await Promise.all(productPromises);

              console.log("productInfos", productInfos);

              // 获取所有地址信息
              const addrPromises = this.merlist.map(item =>
                  getCustomerAddr(this.order.customerId, item.addressId)
                      .then(response => ({
                        ...response.data,
                        addressId: item.addressId // 保留原始addressId
                      }))
              );

              const addrInfos = await Promise.all(addrPromises);

              // 创建映射表
              const productInfoMap = productInfos.reduce((acc, info) => {
                if (info && info.productId) {
                  acc[info.productId] = info;
                }
                return acc;
              }, {});

              // 合并数据
              this.enrichedOrderDetails = this.merlist.map((item, index) => {
                const addr = addrInfos[index] || {};
                const productInfo = productInfoMap[item.productId] || {};
                console.log("productInfo", productInfo)
                return {
                  ...item,
                  productId: item.productId,
                  productName: productInfo.productName,
                  productCategory: productInfo.type,
                  specification: productInfo.specification,
                  source: productInfo.source,
                  price: productInfo.price,
                  addressId: item.addressId,
                  customerAddr: `${addr.state || ''} ${addr.city || ''} ${addr.district || ''} ${addr.streetAddress || ''}`.trim(),
                  subtotal: productInfo.price * item.productSalesQuantity
                };
              });

              console.log("enrichedOrderDetails", this.enrichedOrderDetails);
              this.enrichedOrderDetails.sort((a, b) =>
                  a.customerAddr.localeCompare(b.customerAddr)
              );
              this.calculateSpans();
              this.getOrderTotal();
              this.getMerAddListInfo();
            } catch (error) {
              console.error('无法丰富订单详情：', error);
            }
          },

          getDictsType(){

             getDicts("business_type").then(response =>{
                 this.businessType = response.data;
             }).catch(error =>{
                 console.error(error);
                 throw error;
             })

              getDicts('payment_meth').then(response =>{
                this.paymentType = response.data
              }).catch(error =>{
                console.error(error);
                throw error;
              })


           },

          getBusiness(){
              getData(parseInt(this.order.businessType )+108).then(response =>{
                  this.business = response.data;
              }).catch(error =>{
                  console.error(error);
                  throw error;
              })
          },

          getpayDict(){
             getData(parseInt(this.order.paymentMethod )+111).then(response =>{
                 this.payment = response.data;
             }).catch(error =>{
                 console.error(error);
                 throw error;
             })
          },

          getCustomerAddr() {
            getCustomerAddr(this.order.customerId,this.order.addressId).then(response => {
              this.customerAddr = response.data;
            }).catch(error => {
              console.error(error);
              throw error;
            });
          },

          getAddr(){
            return this.customerAddr.country +"-"+ this.customerAddr.city +"-"+
                    this.customerAddr.state + "-"+this.customerAddr.district +"-"+
                    this.customerAddr.streetAddress;
          },

          getTitle(value){

              return this.steps[parseInt(value)].title;
          },

          getMerList(){
            getDetail(this.order.orderId).then(response =>{
                this.merlist = response.data;
                console.log("mmmm",this.merlist)
                this.fetchAndEnrichOrderDetails();
                console.log("1111111",this.enrichedOrderDetails)
            }) .catch(error =>{
                console.error(error);
                throw error;
            })
          },

         getDescription(index) {
             const activeIndex = this.formatStepStatus(this.order.orderStatus);

             return index <= activeIndex ? this.order.modifiedDate: '';
         },


        formatStepStatus(value) {

         return parseInt(value)-1;
        },

    }






    }
</script>

<style scoped>
    .detail-container {
        width: 90%;
        padding: 20px 20px 20px 20px;
        margin: 20px auto;
    }

    .operate-container {
        background: #F2F6FC;
        height: 80px;
        margin: -20px -20px 0;
        line-height: 80px;
    }

    .operate-button-container {
        float: right;
        margin-right: 20px
    }

    .table-layout {
        margin-top: 20px;
        border-left: 1px solid #DCDFE6;
        border-top: 1px solid #DCDFE6;
    }

    .table-cell {
        height: 60px;
        line-height: 40px;
        border-right: 1px solid #DCDFE6;
        border-bottom: 1px solid #DCDFE6;
        padding: 10px;
        font-size: 14px;
        color: #606266;
        text-align: center;
        overflow: hidden;
    }

    .table-cell-title {
        border-right: 1px solid #DCDFE6;
        border-bottom: 1px solid #DCDFE6;
        padding: 10px;
        background: #F2F6FC;
        text-align: center;
        font-size: 14px;
        color: #303133;
    }
</style>